import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  Modal,
  Divider,
  Steps,
  TreeSelect,
  Checkbox,
  Row,
  Col,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './Class.less';

const FormItem = Form.Item;
const { Step } = Steps;
const { Option } = Select;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@Form.create()
class UpdateClass extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      formVals: {
        name: props.values.name,
        key: props.values.key,
        pid: props.values.pid,
      },
    };
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  updateModa = e => {
    const { form, handUpdateClass } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handUpdateClass(fieldsValue);
    });
  };

  modalFootContent = () => {
    const { handleUpdateClassVisible } = this.props;
    return [
      <Button key="cancel" onClick={() => handleUpdateClassVisible(false)}>
        取消
      </Button>,
      <Button key="submit" type="primary" onClick={() => this.updateModa()}>
        完成
      </Button>,
    ];
  };

  render() {
    const { updateClassVisible, handleUpdateClassVisible, list, values, form } = this.props;
    console.log(list.selectData, values.pid);
    return (
      <Modal
        title="修改分类"
        visible={updateClassVisible}
        maskClosable={true}
        onCancel={() => handleUpdateClassVisible(false)}
        footer={this.modalFootContent()}
      >
        <Form onSubmit={this.updateModa}>
          <FormItem key="key">
            {form.getFieldDecorator('key', {
              initialValue: values.key,
            })(<Input type="hidden" />)}
          </FormItem>
          ,
          <FormItem key="pid" {...this.formLayout} label="上级">
            {form.getFieldDecorator('pid', {
              initialValue: values.pid,
            })(
              <TreeSelect
                style={{ width: 250 }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={list.selectData}
                placeholder="请选择"
                treeDefaultExpandedKeys={[values.id]}
              />
            )}
          </FormItem>
          ,
          <FormItem key="title" {...this.formLayout} label="名称">
            {form.getFieldDecorator('title', {
              rules: [{ required: true, message: '请输入角色名称！' }],
              initialValue: values.title,
            })(<Input placeholder="请输入" />)}
          </FormItem>
          ,
        </Form>
      </Modal>
    );
  }
}

@Form.create()
class CreaateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }

  createModal = () => {
    const { form, handCreateClass } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handCreateClass(fieldsValue);
    });
  };

  modalFootContent = () => {
    const { handleUpdateClassVisible } = this.props;
    return [
      <Button key="cancel" onClick={() => handleUpdateClassVisible(false)}>
        取消
      </Button>,
      <Button key="submit" type="primary" onClick={() => this.createModal()}>
        完成
      </Button>,
    ];
  };

  render() {
    const { createClassVisible, handleCreateClassVisible, list, form } = this.props;
    return (
      <Modal
        visible={createClassVisible}
        title="新建分类"
        maskClosable={true}
        onCancel={() => handleCreateClassVisible(false)}
        footer={this.modalFootContent()}
      >
        <Form onSubmit={this.createModal}>
          <FormItem key="pid" {...this.formLayout} label="上级">
            {form.getFieldDecorator('pid', {
              rules: [{ required: true, message: '请选择分类' }],
            })(
              <TreeSelect
                style={{ width: 250 }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={list.selectData}
                placeholder="请选择"
              />
            )}
          </FormItem>
          ,
          <FormItem key="title" {...this.formLayout} label="名称">
            {form.getFieldDecorator('title', {
              rules: [{ required: true, message: '请输入角色名称！' }],
            })(<Input placeholder="请输入" />)}
          </FormItem>
          ,
        </Form>
      </Modal>
    );
  }
}

@connect(({ crowd, loading }) => ({
  crowd,
  loading: loading.models.crowd,
}))
@Form.create()
class Class extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
    stepFormValues: {},
    updateClassVisible: false,
    createClassVisible: false,
  };

  columns = [
    {
      title: '分类名称',
      dataIndex: 'title',
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleUpdateClassVisible(true, record)}>
            <Icon type="edit" theme="twoTone" /> 配置
          </a>
          <Divider type="vertical" />
          <a onClick={() => this.showConfirm(record)}>
            <Icon type="delete" theme="twoTone" /> 删除
          </a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'crowd/fetchCrowdClassList',
    });
  }

  showConfirm(record) {
    const { dispatch } = this.props;
    Modal.confirm({
      title: '删除分类?',
      content: '是否删除该分类，删除之后所有的下级分类都会删除！！！',
      okText: '是',
      okType: 'danger',
      cancelText: '否',
      onOk() {
        dispatch({
          type: 'crowd/fetchCrowdClassRemove',
          payload: {
            key: record.key,
          },
        });
      },
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'crowd/fetchCrowdClassList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'crowd/fetchCrowdClassList',
      payload: {},
    });
  };

  handleMenuClick = e => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;
    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'crowd/fetchCrowdClassList',
          payload: {
            key: selectedRows.map(row => row.key),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleUpdateClassVisible = (flag, item) => {
    this.setState({
      updateClassVisible: !!flag,
      stepFormValues: item || {},
    });
  };

  handleCreateClassVisible = flag => {
    this.setState({
      createClassVisible: !!flag,
    });
  };

  handUpdateClass = values => {
    const { dispatch } = this.props;
    if (values.pid === '没有上级') {
      values.pid = 0;
    }
    dispatch({
      type: 'crowd/fetchCrowdClassUpdate',
      payload: values,
    });
    this.handleUpdateClassVisible(false, {});
  };

  handCreateClass = values => {
    const { dispatch } = this.props;
    dispatch({
      type: 'crowd/fetchCrowdClassAdd',
      payload: values,
    });
    this.handleCreateClassVisible(false);
  };

  render() {
    const {
      crowd: { list },
      loading,
    } = this.props;
    const { selectedRows, updateClassVisible, stepFormValues, createClassVisible } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick} selectedKeys={[]}>
        <Menu.Item key="remove">删除</Menu.Item>
        <Menu.Item key="approval">批量审批</Menu.Item>
      </Menu>
    );
    const updateMethods = {
      handleUpdateClassVisible: this.handleUpdateClassVisible,
      handUpdateClass: this.handUpdateClass,
    };
    const createMethods = {
      handleCreateClassVisible: this.handleCreateClassVisible,
      handCreateClass: this.handCreateClass,
    };
    return (
      <PageHeaderWrapper title="群分类管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm} />
            <div className={styles.tableListOperator}>
              <Button
                icon="plus"
                type="primary"
                onClick={() => this.handleCreateClassVisible(true)}
              >
                新建
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button>批量操作</Button>
                  <Dropdown overlay={menu}>
                    <Button>
                      更多操作 <Icon type="down" />
                    </Button>
                  </Dropdown>
                </span>
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={list}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              pagination={false}
            />
          </div>
        </Card>
        <CreaateForm {...createMethods} list={list} createClassVisible={createClassVisible} />
        {stepFormValues && Object.keys(stepFormValues).length ? (
          <UpdateClass
            {...updateMethods}
            list={list}
            updateClassVisible={updateClassVisible}
            values={stepFormValues}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default Class;
